package main

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"github.com/olivere/elastic/v7"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"io"
	"log"
	"mxshop_srvs/goods_srv/model"
	"os"
	"strconv"
	"time"
)

func getMd5(code string) string {
	Md5 := md5.New()
	_, _ = io.WriteString(Md5, code)
	return hex.EncodeToString(Md5.Sum(nil))
}

/*
*
测试连接数据库
*/
/*func main() {
	//参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := "root:123456@tcp(localhost:3306)/mxshop_order_srv?charset=utf8mb4&parseTime=True&loc=Local"

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      true,        // 禁用彩色打印
		},
	)

	// 全局模式
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		panic(err)
	}
	//设置全局的logger，这个logger在我们执行每个sql语句的时候会打印每一行sql
	//sql才是最重要的，本着这个原则我尽量的给大家看到每个api背后的sql语句是什么

	//定义一个表结构， 将表结构直接生成对应的表 - migrations
	// 迁移 schema
	_ = db.AutoMigrate(&model.Goods{}, &model.Category{}, &model.GoodsCategoryBrand{}, &model.Brands{}, &model.Banner{})

}*/

func main() {
	Mysql2Es()
}

/*
*
将商品的数据导入到es中去
*/
func Mysql2Es() {
	//参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := "root:123456@tcp(localhost:3306)/mxshop_order_srv?charset=utf8mb4&parseTime=True&loc=Local"

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      true,        // 禁用彩色打印
		},
	)

	// 全局模式
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		panic(err)
	}

	var goods []model.Goods
	db.Find(&goods)

	host := "http://192.168.200.143:9200"
	logger := log.New(os.Stdout, "mxshop", log.LstdFlags)
	client, err := elastic.NewClient(elastic.SetURL(host), elastic.SetSniff(false), elastic.SetTraceLog(logger))
	if err != nil {
		panic(err)
	}
	//fmt.Println(client)

	for _, good := range goods {
		esGoods := model.EsGoods{
			ID:          good.ID,
			CategoryID:  good.CategoryID,
			BrandsID:    good.BrandsID,
			OnSale:      good.OnSale,
			ShipFree:    good.ShipFree,
			IsNew:       good.IsNew,
			IsHot:       good.IsHot,
			Name:        good.Name,
			ClickNum:    good.ClickNum,
			SoldNum:     good.SoldNum,
			FavNum:      good.FavNum,
			MarketPrice: good.MarketPrice,
			GoodsBrief:  good.GoodsBrief,
			ShopPrice:   good.ShopPrice,
		}
		//fmt.Println(esGoods)
		_, err := client.Index().
			Index(model.EsGoods{}.GetIndexName()).
			Id(strconv.Itoa(int(good.ID))).
			BodyJson(esGoods).
			Do(context.Background())
		if err != nil {
			// Handle error
			panic(err)
		}
		//fmt.Printf("Indexed my_account %s to index %s, type %s\n", put1.Id, put1.Index, put1.Type)
	}
}
